#  !/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
知识解释智能体系统测试脚本
测试各个模块的功能和集成
"""

from main import KnowledgeExplanationAgent
import json

def test_question_classification():
    """测试问题分类模块"""
    print("=== 测试问题分类模块 ===")
    from question_classifier import QuestionClassifier
    
    classifier = QuestionClassifier()
    test_questions = [
        "生命周期是什么？",
        "如何使用迭代器？", 
        "这个编译错误怎么解决？",
        "Rust和C++有什么区别？",
        "Rust适合什么项目？"
    ]
    
    for question in test_questions:
        result = classifier.classify(question)
        print(f"问题: {question}")
        print(f"分类: {result['label']} (置信度: {result['confidence']:.3f})")
        print()

def test_semantic_retrieval():
    """测试语义检索模块"""
    print("=== 测试语义检索模块 ===")
    from semantic_retriever import SemanticRetriever
    
    retriever = SemanticRetriever()
    test_questions = [
        "生命周期",
        "所有权",
        "可变变量",
        "借用检查器错误"
    ]
    
    for question in test_questions:
        results = retriever.retrieve(question)
        print(f"检索问题: {question}")
        print(f"找到 {len(results)} 个相关文档:")
        for doc in results:
            print(f"  - {doc['topic']} (分数: {doc['score']:.3f})")
        print()

def test_answer_generation():
    """测试回答生成模块"""
    print("=== 测试回答生成模块 ===")
    from answer_generator import AnswerGenerator
    from semantic_retriever import SemanticRetriever
    
    generator = AnswerGenerator()
    retriever = SemanticRetriever()
    
    question = "生命周期是什么？"
    classification = {"label": "definition", "confidence": 0.9}
    docs = retriever.retrieve(question, "definition")
    
    answer = generator.generate(question, classification, docs, [])
    print(f"问题: {question}")
    print(f"生成的回答:\n{answer}")
    print()

def test_context_management():
    """测试上下文管理模块"""
    print("=== 测试上下文管理模块 ===")
    from context_manager import ContextManager
    
    manager = ContextManager()
    session_id = "test_session_001"
    
    # 模拟多轮对话
    conversations = [
        ("生命周期是什么？", "生命周期是...", {"label": "definition", "confidence": 0.9}),
        ("如何使用生命周期？", "使用生命周期...", {"label": "usage", "confidence": 0.8}),
        ("为什么会出现生命周期错误？", "生命周期错误...", {"label": "error_debug", "confidence": 0.7})
    ]
    
    for question, answer, classification in conversations:
        manager.update_context(session_id, question, answer, classification)
    
    # 获取上下文
    context = manager.get_context(session_id)
    print(f"会话 {session_id} 的上下文:")
    for turn in context:
        print(f"  轮次 {turn['turn_id']}: {turn['question']}")
    
    # 获取会话摘要
    summary = manager.get_session_summary(session_id)
    print(f"\n会话摘要: {json.dumps(summary, ensure_ascii=False, indent=2)}")
    print()

def test_multimodal_rendering():
    """测试多模态渲染模块"""
    print("=== 测试多模态渲染模块 ===")
    from multimodal_renderer import MultimodalRenderer
    
    renderer = MultimodalRenderer()
    
    # 测试Markdown内容
    test_markdown = """
# Rust生命周期详解

## 概念定义
**生命周期**是Rust中引用保持有效的作用域。

## 示例代码
```rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}
```

## 流程图
```mermaid
graph TD
    A[创建引用] --> B[生命周期开始]
    B --> C[使用引用]
    C --> D[生命周期结束]
    D --> E[引用失效]
```

## 关键要点
1. 生命周期确保引用安全
2. 编译器自动推断生命周期
3. 显式标注用于复杂情况
"""
    
    html = renderer.render(test_markdown)
    print("生成的HTML长度:", len(html))
    print("HTML预览:", html[:200] + "...")
    
    # 保存HTML文件
    renderer.save_html(test_markdown, "test_output.html")
    print("HTML文件已保存为 test_output.html")
    print()

def test_full_system():
    """测试完整系统"""
    print("=== 测试完整系统 ===")
    agent = KnowledgeExplanationAgent()
    
    test_cases = [
        ("生命周期是什么？", "user_001"),
        ("如何使用可变变量？", "user_002"),
        ("Rust和C++有什么区别？", "user_003")
    ]
    
    for question, user_id in test_cases:
        print(f"用户 {user_id} 提问: {question}")
        result = agent.process_question(user_id, question)
        
        if result['status'] == 'success':
            print(f"  问题类型: {result['classification']['label']}")
            print(f"  置信度: {result['classification']['confidence']:.3f}")
            print(f"  上下文长度: {result['context_length']}")
            print(f"  回答长度: {len(result['answer_markdown'])} 字符")
        else:
            print(f"  错误: {result['message']}")
        print()

if __name__ == "__main__":
    print("开始测试知识解释智能体系统...\n")
    
    try:
        test_question_classification()
        test_semantic_retrieval()
        test_answer_generation()
        test_context_management()
        test_multimodal_rendering()
        test_full_system()
        
        print("所有测试完成！")
        
    except Exception as e:
        print(f"测试过程中出现错误: {e}")
        import traceback
        traceback.print_exc() 